import { Form, Input, InputNumber, Button, Row, Col, message, } from 'antd';
import React, { useState, useEffect, } from 'react';
import $utils from '@/utils/utils';
import { useModel, history } from 'umi';
import styles from './index.less';
import { getPcode, resetPassword } from '@/services/user';

let timer: NodeJS.Timeout;

const ForgetPwd: React.FC = () => {


    const [form] = Form.useForm();

    const [verifyTime, setVerifyTime] = useState<number>(60);
    const [codeState, setCodeState] = useState<boolean>(false);
    const { initialState, setInitialState } = useModel('@@initialState');

    const l_state: any = history.location.state;

    const setUserInfo = async (userInfo: API.CurrentUser) => {
        if (userInfo) {
            initialState?.setRegionList?.(userInfo);
            await setInitialState((s) => ({
                ...s,
                currentUser: userInfo,
            }));
        }
    };

    const onFinish = async (values: any) => {
        const msg = await resetPassword({ ...values });
        if (msg.code === 0) {
            message.success('修改成功');
            $utils.setStorage('user_info', msg.body, 2 * 3600 * 1000);
            await setUserInfo(msg.body);


            /** 此方法会跳转到 redirect 参数所在的位置 */
            if (!history) return;
            const { query } = history.location;
            const { redirect } = query as { redirect: string };
            history.push(redirect || '/');
            return;
        }
    };

    const onFinishFailed = (errorInfo: any) => {
        console.log('Failed:', errorInfo);
    };

    const handleGetCode = async () => {
        const phone = form.getFieldValue('phone');
        if (!phone) {
            return message.error('请先输入手机号');
        }
        // 先请求获取验证码接口再进行计时
        const msg = await getPcode({ phone });
        if (msg.code === 0) {
            setCodeState(true);
            let a = 60;
            timer = setInterval(function () {
                a = a - 1;
                setVerifyTime(a);
            }, 1000);
        }
    }

    useEffect(() => {
        if (codeState && verifyTime <= 0) {
            clearInterval(timer);
            setCodeState(false);
            setVerifyTime(60);
        }
    }, [verifyTime]);

    return (
        <div className={styles.container}>
            <div className={styles.content}>
                {l_state === 'init' && <div style={{ color: 'red', marginBottom: 50, paddingLeft: 45, fontSize: 18 }}>您当前为第一次登录，修改初始密码后才可登录系统</div>}
                <Form
                    className={styles.Form}
                    form={form}
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 16 }}
                    initialValues={{ remember: true }}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                    autoComplete="off"
                >
                    <Form.Item
                        label="手机号"
                        name="phone"
                        rules={[{ required: true, }]}
                    >
                        <Input maxLength={11} placeholder={"请输入手机号"} />
                    </Form.Item>

                    <Form.Item
                        label="验证码"
                        rules={[{ required: true, }]}
                        name="pcode"
                    >
                        <Row gutter={24}>
                            <Col span={12}>
                                <Form.Item
                                    noStyle
                                >
                                    <InputNumber placeholder={"请输入验证码"} maxLength={6} style={{ width: 120 }} controls={false} />
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Button type="primary" disabled={codeState} onClick={() => {
                                    handleGetCode();
                                }}>{!codeState ? '获取验证码' : `重新获取(${verifyTime})`}</Button>
                            </Col>
                        </Row>
                    </Form.Item>
                    <Form.Item
                        label="新密码"
                        name="password"
                        rules={[
                            { required: true },
                            {
                                pattern: new RegExp('^(?![A-Za-z0-9]+$)(?![a-z0-9\\W]+$)(?![A-Za-z\\W]+$)(?![A-Z0-9\\W]+$)[a-zA-Z0-9\\W]{8,20}$', 'g'),
                                message: '密码需为8-20位，同时包含大小写字母+数字+符号'
                            }
                        ]}
                    >
                        <Input.Password maxLength={20} placeholder={"请输入新密码"} />
                    </Form.Item>
                    <Form.Item
                        label="确认密码"
                        name="new_password"
                        rules={[
                            { required: true, },
                            ({ getFieldValue }) => ({
                                validator(_, value) {
                                    if (value !== getFieldValue('password')) {
                                        return Promise.reject(new Error('请与新密码保持一致'))
                                    }
                                    return Promise.resolve();
                                }
                            }),
                        ]}
                    >
                        <Input.Password maxLength={20} placeholder={"请再次输入新密码"} />
                    </Form.Item>

                    <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                        <Button type="primary" block htmlType="submit">
                            提交
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        </div>
    );
};

export default ForgetPwd;
